# coding=utf-8
import os
import time
from function_utils import Global, Human, PsUtil, Common


def date():
    return Human.time().replace(',', '-')


class WatchSys(object):

    def __init__(self):
        # 停止旧版本的watch进程 #
        Common.execute_cmd('killall watch_system.sh')
        Common.execute_cmd('rm -rf /opt/Bingo')

        PsUtil.init()
        self.mem_infos = None
        self.cpu_infos = None
        self.disk_infos = None
        self.net_recv = None
        self.net_send = None

    def watch_mem(self, args=None):
        percent = int(PsUtil.memory()['mem_percent'])
        head = 'Date,Memory-Used%'
        self.mem_infos = ('system_memory.csv', 'Percent', [0, 100], "%s %s %s" % (date(), head, percent))

    def watch_cpu(self):
        # CPUs, CPU-0, CPU-1, ...
        start, head, cpus = [], ['Date'], []
        for cpu in PsUtil.cpu_times():
            total = sum(cpu)
            idle = cpu[3]
            start.append((total, idle))
        time.sleep(5)
        for i, cpu in enumerate(PsUtil.cpu_times()):
            total = sum(cpu)
            idle = cpu[3]
            percent = (1 - (idle - start[i][1]) / float(total - start[i][0])) * 100
            cpus.append(str(int(percent)))
            if i == 0:
                head.append('CPUs-Used%')
            else:
                head.append('CPU%s-Used%%' % i)
        self.cpu_infos = ('system_cpu.csv', 'Percent', [0, 100], '%s %s %s' % (date(), ','.join(head), ','.join(cpus)))

    def watch_disk(self):
        last = PsUtil.diskstats()
        time.sleep(5)
        curr = PsUtil.diskstats()
        head, per = ['Date'], []
        for dev, stat in curr.items():
            per.append(str(int(stat['tot_ticks'] - last[dev]['tot_ticks']) / (stat["ts"] - last[dev]["ts"]) / 10))
            head.append('%s-Util%%' % dev)
        self.disk_infos = ('system_disk.csv', 'Percent', [0, 100], '%s %s %s' % (date(), ','.join(head), ','.join(per)))

    def watch_net(self):
        interval = 5
        last = PsUtil.net_io()
        time.sleep(interval)
        curr = PsUtil.net_io()
        r_head, s_head, r_per, s_per = ['Date'], ['Date'], [], []
        for dev, nets in curr.items():
            r_head.append('%s-recv' % dev)
            s_head.append('%s-send' % dev)
            last_nets = last[dev]
            recv = nets['bytes_recv']
            send = nets['bytes_sent']
            r_per.append(str((recv - last_nets['bytes_recv']) / interval / 1024))
            s_per.append(str((send - last_nets['bytes_sent']) / interval / 1024))
        self.net_recv = ('system_net_recv.csv', 'KB/s', [], '%s %s %s' % (date(), ','.join(r_head), ','.join(r_per)))
        self.net_send = ('system_net_send.csv', 'KB/s', [], '%s %s %s' % (date(), ','.join(s_head), ','.join(s_per)))


def store_csv_file(data):
    file, label, scale, infos = data
    path = '%s/%s' % (Global.plots_path, file)
    date, head, val = infos.split()
    if not os.path.isfile(path):
        with open(path, 'w') as f:
            f.write('%s\n%s,%s\n' % (head, date, val))
        Common.execute_cmd('chmod 777 %s' % path)
        return
    with open(path, 'a') as f:
        f.write('%s,%s\n' % (date, val))
    Global.plots_record(file, width=800, height=300, dpi=80, label=label, scale=scale)


if __name__ == '__main__':
    w = WatchSys()
    th1 = Common.create_thread(func=w.watch_mem)
    th2 = Common.create_thread(func=w.watch_cpu)
    th3 = Common.create_thread(func=w.watch_disk)
    th4 = Common.create_thread(func=w.watch_net)
    th1.join()
    th2.join()
    th3.join()
    th4.join()
    Global.plots_init()
    store_csv_file(w.mem_infos)
    store_csv_file(w.cpu_infos)
    store_csv_file(w.disk_infos)
    store_csv_file(w.net_recv)
    store_csv_file(w.net_send)

